package com.daydayup.learn;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABADemo {

    private static AtomicStampedReference atomicStampedReference = new AtomicStampedReference(100,1);

    public static void main(String[] args) {

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"\t第一次版本号:"+ stamp);
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
            boolean result = atomicStampedReference.compareAndSet(100, 50, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName()+ (result ? "成功":"失败"));
            System.out.println(Thread.currentThread().getName()+"\t第二次版本号:"+ atomicStampedReference.getStamp());
        },"A").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"\t第一次版本号:"+ stamp);
            try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}
            boolean result = atomicStampedReference.compareAndSet(100, 50, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName()+"\t修改是否成功:"+result+"\t 当前实际版本号:"+ atomicStampedReference.getStamp());
            System.out.println("当前实际最新值:"+atomicStampedReference.getReference());
        },"B").start();

        new Thread(() -> {
            try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"\t第一次版本号:"+ stamp);
            boolean result = atomicStampedReference.compareAndSet(50, 100, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName()+ (result ? "成功":"失败"));
            System.out.println(Thread.currentThread().getName()+"\t第二次版本号:"+ atomicStampedReference.getStamp());
        },"C").start();
    }
}
